<template>
	<view class="login-page">
		<!-- 背景装饰 -->
		<view class="background-container">
			<view class="bg-pattern bg-pattern-1"></view>
			<view class="bg-pattern bg-pattern-2"></view>
			<view class="bg-pattern bg-pattern-3"></view>
		</view>
		
		<!-- 主要内容 -->
		<view class="content-container">
			<!-- Logo 和标题区域 -->
			<view class="header-section">
				<!-- <view class="logo-container">
					<image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
				</view> -->
				<view class="title-section">
					<text class="app-title">{{appTitle}}</text>
					<text class="app-subtitle">{{appSubtitle}}</text>
				</view>
			</view>
			
			<!-- 登录表单 -->
			<view class="form-container">
				<view class="form-card">
					<view class="form-header">
						<text class="form-title">欢迎回来</text>
						<text class="form-subtitle">请登录您的账户</text>
					</view>
					
					<form class="login-form">
						<!-- 用户名输入 -->
						<view class="input-group">
							<view class="input-container" :class="{ 'input-focused': usernameFocused, 'input-error': usernameError }">
								<view class="input-icon">
									<text class="icon">👤</text>
								</view>
								<input 
									class="input-field"
									type="text" 
									placeholder="请输入用户名" 
									v-model="formData.username"
									@focus="usernameFocused = true"
									@blur="usernameFocused = false"
									@input="clearUsernameError"
									maxlength="20"
								/>
							</view>
							<text v-if="usernameError" class="error-text">{{usernameError}}</text>
						</view>
						
						<!-- 密码输入 -->
						<view class="input-group">
							<view class="input-container" :class="{ 'input-focused': passwordFocused, 'input-error': passwordError }">
								<view class="input-icon">
									<text class="icon">🔒</text>
								</view>
								<input 
									class="input-field"
									:type="passwordVisible ? 'text' : 'password'"
									placeholder="请输入密码" 
									v-model="formData.password"
									@focus="passwordFocused = true"
									@blur="passwordFocused = false"
									@input="clearPasswordError"
									maxlength="20"
								/>
								<view class="password-toggle" @click="togglePasswordVisibility">
									<text class="toggle-icon">{{passwordVisible ? '👁️' : '🙈'}}</text>
								</view>
							</view>
							<text v-if="passwordError" class="error-text">{{passwordError}}</text>
						</view>
						
						<!-- 角色选择 -->
						<view class="input-group">
							<view class="input-container" :class="{ 'input-focused': roleFocused, 'input-error': roleError }">
								<view class="input-icon">
									<text class="icon">👨‍💼</text>
								</view>
								<picker 
									class="role-picker"
									mode="selector" 
									:value="selectedRoleIndex" 
									:range="roleOptions"
									range-key="name"
									@change="handleRoleChange"
									@focus="roleFocused = true"
									@blur="roleFocused = false"
								>
									<view class="picker-content">
										<text class="picker-text" :class="{ 'placeholder': !formData.role }">{{selectedRoleName || '请选择登录角色'}}</text>
										<text class="dropdown-icon">▼</text>
									</view>
								</picker>
							</view>
							<text v-if="roleError" class="error-text">{{roleError}}</text>
						</view>
						
						<!-- 选项 -->
						<view class="form-options">
							<view class="remember-me" @click="toggleRememberMe">
								<view class="checkbox" :class="{ 'checked': rememberMe }">
									<text v-if="rememberMe" class="check-icon">✓</text>
								</view>
								<text class="option-text">记住密码</text>
							</view>
							<view class="forgot-password" @click="handleForgotPassword">
								<text class="link-text">忘记密码？</text>
							</view>
						</view>
						
						<!-- 登录按钮 -->
						<view class="button-group">
							<button 
								class="btn btn-primary btn-login" 
								:class="{ 'btn-loading': isLoading }"
								@click="handleLogin"
								:disabled="isLoading"
							>
								<view v-if="isLoading" class="loading-spinner"></view>
								<text class="btn-text">{{isLoading ? '登录中...' : '登 录'}}</text>
							</button>
							
							<!-- <button class="btn btn-secondary btn-guest" @click="handleGuestMode">
								<text class="btn-text">游客模式</text>
							</button> -->
						</view>
					</form>
				</view>
			</view>
			
			<!-- 底部信息 -->
			<view class="footer-section">
				<view class="version-info">
					<text class="version-text">v{{appVersion}}</text>
				</view>
				<view class="copyright">
					<text class="copyright-text">© 2024 水务工程管控系统</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import { request } from '@/request/index.js'
	import { APP_INFO, STORAGE_KEYS, USER_ROLES } from '@/constants/index.js'
	import { setStorage, showToast, showLoading, hideLoading, isValidPhone } from '@/utils/index.js'

	export default {
		data() {
			return {
				// 应用信息
				appTitle: APP_INFO.name,
				appSubtitle: APP_INFO.description,
				appVersion: APP_INFO.version,
				
				// 表单数据
				formData: {
					username: 'yangf', // 测试用户名
					password: 'ComeOn~2025', // 测试密码
					role: '' // 选中的角色
				},
				
				// 角色相关
				roleOptions: [
					{ code: 'supervisor', name: '建设方项目负责人',username:'15926244226',password:'121' },
					{ code: 'manager', name: '质监站科员',username:'13367277685',password:'121' },
					{ code: 'quality_manager', name: '施工方项目负责人',username:'13871331191',password:'1' },
					{ code: 'safety_manager', name:'质监站科员',username:'15871696126',password:'121' },
					{ code: 'site_manager', name: '质监站负责人' ,username:'13971604751',password:'121'},
					{ code: 'admin', name: '信息管理员' ,username:'yangf',password:'ComeOn~2025'}
				],
				selectedRoleIndex: -1,
				
				// 表单状态
				usernameFocused: false,
				passwordFocused: false,
				roleFocused: false,
				passwordVisible: false,
				rememberMe: false,
				isLoading: false,
				
				// 错误信息
				usernameError: '',
				passwordError: '',
				roleError: ''
			}
		},
		
		computed: {
			/**
			 * 获取当前选中的角色名称
			 */
			selectedRoleName() {
				if (this.selectedRoleIndex >= 0 && this.selectedRoleIndex < this.roleOptions.length) {
					this.formData.username = this.roleOptions[this.selectedRoleIndex].username
					this.formData.password = this.roleOptions[this.selectedRoleIndex].password
					return this.roleOptions[this.selectedRoleIndex].name
				}
				return ''
			}
		},
		
		onLoad() {
			this.loadSavedCredentials()
		},
		
		methods: {
			/**
			 * 加载已保存的登录信息
			 */
			loadSavedCredentials() {
				try {
					const savedUsername = uni.getStorageSync('saved_username')
					const savedRememberMe = uni.getStorageSync('remember_me')
					
					if (savedRememberMe && savedUsername) {
						this.formData.username = savedUsername
						this.rememberMe = true
					}
				} catch (error) {
					console.error('加载保存的登录信息失败:', error)
				}
			},
			
			/**
			 * 验证表单
			 */
			validateForm() {
				let isValid = true
				
				// 验证用户名
				if (!this.formData.username.trim()) {
					this.usernameError = '请输入用户名'
					isValid = false
				} else if (this.formData.username.length < 3) {
					this.usernameError = '用户名至少3位字符'
					isValid = false
				}
				
				// 验证密码
				if (!this.formData.password.trim()) {
					this.passwordError = '请输入密码'
					isValid = false
				} 
				// if (this.formData.password.length < 6) {
				// 	this.passwordError = '密码至少6位字符'
				// 	isValid = false
				// }
				
				// 验证角色
				if (!this.formData.role) {
					this.roleError = '请选择登录角色'
					isValid = false
				}
				
				return isValid
			},
			
			/**
			 * 处理登录
			 */
			async handleLogin() {
				// 清除之前的错误信息
				this.clearAllErrors()
				
				// 验证表单
				if (!this.validateForm()) {
					return
				}
				
				this.isLoading = true
				
				try {
					const loginData = {
						username: this.formData.username.trim(),
						pwd: this.formData.password.trim(),
						role: this.formData.role // 添加角色信息
					}
					
					const response = await request({
						url: '/thirdLogin',
						data: loginData,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'third': true
						}
					})
					
					if (response.data.code === '200') {
						// 登录成功
						await this.handleLoginSuccess(response)
					} else {
						// 登录失败
						this.handleLoginError(response.data.msg || '登录失败')
					}
				} catch (error) {
					console.error('登录请求失败:', error)
					this.handleLoginError(error)
				} finally {
					this.isLoading = false
				}
			},
			
			/**
			 * 处理登录成功
			 */
			async handleLoginSuccess(response) {
				showToast('登录成功', 'success')
				
				// 保存登录信息
				setStorage(STORAGE_KEYS.TOKEN, response.header['Set-Cookie'])
							
				// 保存用户信息和角色
				const userInfo = {
					...response.data.data,
					role: this.formData.role,
					roleName: this.selectedRoleName
				}
				setStorage(STORAGE_KEYS.USER_INFO, userInfo)
				
				// 保存用户名（如果勾选了记住密码）
				if (this.rememberMe) {
					uni.setStorageSync('saved_username', this.formData.username)
					uni.setStorageSync('remember_me', true)
				} else {
					uni.removeStorageSync('saved_username')
					uni.removeStorageSync('remember_me')
				}
				
				// 跳转到首页
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}, 500)
			},
			
			/**
			 * 处理登录错误
			 */
			handleLoginError(error) {
				let errorMsg = '登录失败'
				
				// 处理网络错误
				if (error && error.errMsg) {
					if (error.errMsg.includes('Network Error')) {
						errorMsg = '网络连接失败，请检查网络设置'
					} else if (error.errMsg.includes('timeout')) {
						errorMsg = '请求超时，请稍后重试'
					} else if (error.errMsg.includes('CERT')) {
						errorMsg = '证书验证失败，请联系管理员'
					}
				} else if (typeof error === 'string') {
					errorMsg = error
				}
				
				showToast(errorMsg, 'none')
				
				// 根据错误类型设置具体的错误信息
				if (errorMsg.includes('用户名') || errorMsg.includes('账号')) {
					this.usernameError = '用户名不存在'
				} else if (errorMsg.includes('密码')) {
					this.passwordError = '密码错误'
				}
			},
			
			/**
			 * 处理游客模式
			 */
			handleGuestMode() {
				uni.showModal({
					title: '游客模式',
					content: '游客模式下功能有限，建议登录后使用完整功能',
					confirmText: '继续',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					}
				})
			},
			
			/**
			 * 处理忘记密码
			 */
			handleForgotPassword() {
				uni.showModal({
					title: '忘记密码',
					content: '请联系管理员重置密码',
					showCancel: false
				})
			},
			
			/**
			 * 处理角色变更
			 */
			handleRoleChange(e) {
				this.selectedRoleIndex = e.detail.value
				if (this.selectedRoleIndex >= 0) {
					console.log(this.roleOptions[this.selectedRoleIndex])
					this.formData.role = this.roleOptions[this.selectedRoleIndex].code
					this.formData.username = this.roleOptions[this.selectedRoleIndex].username
					this.formData.password = this.roleOptions[this.selectedRoleIndex].password
					this.clearRoleError()
				}
			},
			
			/**
			 * 切换密码可见性
			 */
			togglePasswordVisibility() {
				this.passwordVisible = !this.passwordVisible
			},
			
			/**
			 * 切换记住密码
			 */
			toggleRememberMe() {
				this.rememberMe = !this.rememberMe
			},
			
			/**
			 * 清除用户名错误
			 */
			clearUsernameError() {
				this.usernameError = ''
			},
			
			/**
			 * 清除密码错误
			 */
			clearPasswordError() {
				this.passwordError = ''
			},
			
			/**
			 * 清除角色错误
			 */
			clearRoleError() {
				this.roleError = ''
			},
			
			/**
			 * 清除所有错误
			 */
			clearAllErrors() {
				this.usernameError = ''
				this.passwordError = ''
				this.roleError = ''
			}
		}
	}
</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';

.login-page {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	position: relative;
	background: $primary-gradient;
	overflow: hidden;
}

/* 背景装饰 */
.background-container {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	pointer-events: none;
	overflow: hidden;
}

.bg-pattern {
	position: absolute;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.05);
	animation: float 6s ease-in-out infinite;
	
	&.bg-pattern-1 {
		width: 300rpx;
		height: 300rpx;
		top: -100rpx;
		right: -100rpx;
		animation-delay: 0s;
	}
	
	&.bg-pattern-2 {
		width: 200rpx;
		height: 200rpx;
		bottom: 100rpx;
		left: -80rpx;
		animation-delay: 2s;
	}
	
	&.bg-pattern-3 {
		width: 150rpx;
		height: 150rpx;
		top: 50%;
		right: -50rpx;
		animation-delay: 4s;
	}
}

@keyframes float {
	0%, 100% {
		transform: translateY(0) rotate(0deg);
		opacity: 0.3;
	}
	50% {
		transform: translateY(-20rpx) rotate(180deg);
		opacity: 0.1;
	}
}

/* 主要内容区域 */
.content-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: $spacing-xxl $spacing-xl;
	position: relative;
	z-index: 1;
}

/* 顶部区域 */
.header-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	margin-bottom: $spacing-xxl;
	padding-top: $spacing-xxl;
}

.logo-container {
	margin-bottom: $spacing-xl;
}

.logo {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.1);
	padding: $spacing-lg;
	backdrop-filter: $backdrop-filter;
}

.title-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: $spacing-sm;
}

.app-title {
	font-size: $font-size-xxl;
	font-weight: 700;
	color: $text-white;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.app-subtitle {
	font-size: $font-size-base;
	color: rgba(255, 255, 255, 0.8);
	line-height: 1.5;
	max-width: 500rpx;
}

/* 表单容器 */
.form-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.form-card {
	background: rgba(255, 255, 255, 0.95);
	border-radius: $border-radius-xl;
	padding: $spacing-xxl;
	backdrop-filter: $backdrop-filter;
	box-shadow: $shadow-xl;
	border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.form-header {
	text-align: center;
	margin-bottom: $spacing-xxl;
}

.form-title {
	font-size: $font-size-xl;
	font-weight: 600;
	color: $text-primary;
	margin-bottom: $spacing-sm;
	display: block;
}

.form-subtitle {
	font-size: $font-size-base;
	color: $text-secondary;
}

/* 表单样式 */
.login-form {
	display: flex;
	flex-direction: column;
	gap: $spacing-xl;
}

.input-group {
	display: flex;
	flex-direction: column;
	gap: $spacing-sm;
}

.input-container {
	position: relative;
	display: flex;
	align-items: center;
	background: $bg-secondary;
	border: 2rpx solid $border-color;
	border-radius: $border-radius-lg;
	transition: $transition-base;
	height: 96rpx;
	
	&.input-focused {
		border-color: $primary-color;
		box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
	}
	
	&.input-error {
		border-color: $error-color;
		box-shadow: 0 0 0 4rpx rgba(255, 77, 79, 0.1);
	}
}

.input-icon {
	width: 96rpx;
	height: 96rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: $text-secondary;
}

.icon {
	font-size: $font-size-lg;
}

.input-field {
	flex: 1;
	height: 100%;
	padding: 0 $spacing-lg;
	font-size: $font-size-base;
	color: $text-primary;
	background: transparent;
	border: none;
	outline: none;
	
	&::placeholder {
		color: $text-placeholder;
	}
}

.password-toggle {
	width: 96rpx;
	height: 96rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: $transition-base;
	
	&:active {
		transform: scale(0.95);
	}
}

.toggle-icon {
	font-size: $font-size-lg;
	color: $text-secondary;
}

.error-text {
	font-size: $font-size-sm;
	color: $error-color;
	margin-left: $spacing-md;
}

/* 角色选择器样式 */
.role-picker {
	flex: 1;
	height: 100%;
	display: flex;
	align-items: center;
}

.picker-content {
	flex: 1;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 $spacing-lg;
}

.picker-text {
	flex: 1;
	font-size: $font-size-base;
	color: $text-primary;
	
	&.placeholder {
		color: $text-placeholder;
	}
}

.dropdown-icon {
	font-size: $font-size-sm;
	color: $text-secondary;
	transform: rotate(0deg);
	transition: $transition-base;
}

.input-container.input-focused .dropdown-icon {
	transform: rotate(180deg);
}

/* 表单选项 */
.form-options {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.remember-me {
	display: flex;
	align-items: center;
	gap: $spacing-sm;
	cursor: pointer;
}

.checkbox {
	width: 36rpx;
	height: 36rpx;
	border: 2rpx solid $border-color;
	border-radius: $border-radius-sm;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: $transition-base;
	
	&.checked {
		background: $primary-color;
		border-color: $primary-color;
	}
}

.check-icon {
	font-size: $font-size-sm;
	color: $text-white;
	font-weight: bold;
}

.option-text {
	font-size: $font-size-sm;
	color: $text-secondary;
	user-select: none;
}

.forgot-password {
	cursor: pointer;
}

.link-text {
	font-size: $font-size-sm;
	color: $primary-color;
	text-decoration: none;
	transition: $transition-base;
	
	&:active {
		color: $primary-dark;
	}
}

/* 按钮组 */
.button-group {
	display: flex;
	flex-direction: column;
	gap: $spacing-md;
}

.btn {
	height: 96rpx;
	border-radius: $border-radius-lg;
	font-size: $font-size-base;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: $spacing-sm;
	transition: $transition-base;
	border: none;
	outline: none;
	cursor: pointer;
	
	&:active {
		transform: translateY(1rpx);
	}
	
	&.btn-primary {
		background: $primary-gradient;
		color: $text-white;
		box-shadow: $shadow-base;
		
		&:active {
			box-shadow: $shadow-sm;
		}
		
		&.btn-loading {
			opacity: 0.8;
			pointer-events: none;
		}
	}
	
	&.btn-secondary {
		background: transparent;
		color: $text-secondary;
		border: 2rpx solid $border-color;
		
		&:active {
			background: $bg-secondary;
		}
	}
}

.btn-text {
	font-size: inherit;
	color: inherit;
}

.loading-spinner {
	width: 32rpx;
	height: 32rpx;
	border: 3rpx solid rgba(255, 255, 255, 0.3);
	border-top-color: $text-white;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* 底部区域 */
.footer-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: $spacing-sm;
	margin-top: $spacing-xl;
	padding-bottom: $spacing-lg;
}

.version-info {
	padding: $spacing-xs $spacing-sm;
	background: rgba(255, 255, 255, 0.1);
	border-radius: $border-radius-sm;
	backdrop-filter: $backdrop-filter;
}

.version-text {
	font-size: $font-size-xs;
	color: rgba(255, 255, 255, 0.7);
}

.copyright {
	text-align: center;
}

.copyright-text {
	font-size: $font-size-xs;
	color: rgba(255, 255, 255, 0.6);
	line-height: 1.4;
}
</style>